package com.cartagena.financo.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import br.com.caelum.vraptor.Delete;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;

import com.cartagena.financo.model.Category;
import com.cartagena.financo.model.Transaction;
import com.cartagena.financo.repository.CategoryRepository;
import com.cartagena.financo.repository.TransactionRepository;
import com.cartagena.financo.util.DateUtil;
import com.cartagena.vraptor.extjs.ExtJSJson;

@Resource
public class TransactionController {
    
    private final Result result;
    private final TransactionRepository repository; 
    private final CategoryRepository categoryRepository; 
    
    public TransactionController(Result result, TransactionRepository repository, CategoryRepository categoryRepository) {
        this.result = result;
        this.repository = repository;
        this.categoryRepository = categoryRepository;
    }
    
    @Post
    @Path("/transaction/crud")
    public void save(Transaction transaction) {
        repository.add(transaction);
        this.result.use(ExtJSJson.class).from(transaction).success().serialize();
    }
    
    @Post
    @Path("/transaction/crud/{transactiond.id}")
    public void update(Transaction transaction) {
        repository.update(transaction);
        this.result.use(ExtJSJson.class).from(transaction).success().serialize();
    }
    
    @Delete
    @Path("/transaction/crud/{transaction.id}")
    public void remove(Transaction transaction) {
        repository.remove(transaction);
        this.result.use(ExtJSJson.class).from(transaction).success().serialize();
    }
    
    @Get
    @Path("/transaction/crud/{transaction.id}")
    public void get(Transaction transaction) {
        Transaction transactions = repository.get(transaction.getId());
        this.result.use(ExtJSJson.class).from(transactions).success().serialize();
    }
    
    
  //  @Post
    @Path("/transaction/store")
    public void listByCategory(Date begin, Date end, String category) {
        List<Transaction> transactions = new ArrayList<Transaction>();

        if(begin == null) {
            begin = DateUtil.getDefaultDayBegin();
        }
        if(end == null) {
            end = DateUtil.getDefaultDayEnd();
        }
                       
        Category cat = this.categoryRepository.loadByName(category);
                
        transactions = repository.listByCategoryAndPeriod(cat, begin, end);
        this.result.use(ExtJSJson.class).from(transactions).success().serialize();
    }
}
